package com.cml.rpc.server;

import com.cml.rpc.serialize.Decode;
import com.cml.rpc.serialize.Encode;
import com.cml.rpc.serialize.JsonSerialize;
import com.cml.rpc.serialize.ObjectSerialize;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * @author cml
 * @create 2021/7/21 13:32
 */
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    private ServiceProvider serviceProvider;

    public NettyServerInitializer(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
/*        // 消息格式[长度][消息体],解决粘包问题
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
                4,0, 4));
        // 计算当前发送消息的长度，写入前4个字节中
        pipeline.addLast(new LengthFieldPrepender(4));

        // 使用jdk序列化
        pipeline.addLast(new ObjectEncoder());
        pipeline.addLast(new ObjectDecoder(new ClassResolver() {
            @Override
            public Class<?> resolve(String s) throws ClassNotFoundException {
                return Class.forName(s);
            }
        }));*/

        // 使用自定义编解码器
        pipeline.addLast(new Decode());
        pipeline.addLast(new Encode(new ObjectSerialize()));

        pipeline.addLast(new NettyRpcServerHandler(serviceProvider));
    }
}
